var BasketDB = {
	init: function () {
		try {
			if(!window.openDatabase) {
				console.log('Databases are not supported in this browser!');
			} else {
				var shortname = 'BasketDB';
				var version = '0.1';
				var displayname = 'Sapient';
				var maxsize = 102400;
				this.BASKETDB = openDatabase(shortname, version, displayname, maxsize);
				this.create();
			}
		} catch (e) {
			if(e==2) {
                console.log('Invalid database version');
            }
            else {
                console.log('Unknown error: ' + e + '!');
            }
            return;
		}
	},
	create: function() {
		this.BASKETDB.transaction(
				function(transaction) {
					transaction.executeSql('CREATE TABLE IF NOT EXISTS basket(id INTEGER NOT NULL PRIMARY KEY, desc TEXT, prod TEXT NOT NULL, brand TEXT NOT NULL, color TEXT, size TEXT, qty INTEGER NOT NULL, price DECIMAL NOT NULL, path INTEGER NOT NULL);', [], BasketDB.nullDataHandler, BasketDB.errorHandler);
				}
			);
		this.all();
	},
	add: function(o) {
		var o = o;
		var id = o.id;
		var desc = o.desc;
		var prod = o.prod;
		var brand = o.brand;
		var color = o.color;
		var size = o.size;
		var qty = o.qty;
		var price = o.price;
		var path = o.path;
		
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql("INSERT INTO basket(id, desc, prod, brand, color, size, qty, price, path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", [id, desc, prod, brand, color, size, qty, price, path], BasketDB.addToBasketHandler, BasketDB.errorHandler);
			});
	},
	remove: function(id) {
		var id = id;
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('DELETE FROM basket WHERE id=?', [id], BasketDB.removeHandler, BasketDB.errorHandler);	
			});
	},
	update: function(id, o) {
		var id = id;
		var o = o;
		var p = '', q = [];

		for (var i in o) {
			p += i + '=?, ';
			q.push(o[i]);
		}

		q.push(id);
		var statement = 'UPDATE basket SET ' + p.substring(0, p.length - 2) + ' WHERE id=?';

		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql(statement, q, BasketDB.addToBasketHandler);
			});
	},
	all: function() {
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('SELECT * FROM basket', [], BasketDB.dataSelectHandler, BasketDB.errorHandler);
			});
	},
	total: function() {
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('SELECT * FROM basket', [], BasketDB.calcTotalHandler, BasketDB.errorHandler);
			});
	},
	clear: function() {
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('DROP TABLE basket');
			});
	},
	do: function(what) {
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('SELECT * FROM basket', [], BasketDB[what], BasketDB.errorHandler);
			});
	},
	checkdo: function(obj, what) {
		this.tmp = obj;
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('SELECT * FROM basket WHERE id=?', [obj.id], BasketDB[what], BasketDB.errorHandler);
			});
	},
	checkUpdateAdd: function(transaction, results) {
		var o = BasketDB.tmp;
		var l = results.rows.length;
		
		if( l == 1 ) {
			var p = results.rows.item(0);
			console.log('element already exists');
//			console.log('database qty:');
//			console.log(p.qty);
//			console.log('current qty:');
//			console.log(o.qty);
//			console.log('total qty');
//			console.log(Number(p.qty) + Number(o.qty));
			
			o.qty = Number(p.qty) + Number(o.qty);
//			console.log('---------------------------------------');
//			console.log('database object')
//			console.log(o);
//			console.log('---------------------------------------');
			BasketDB.update(o.id, o);
		}
		else
		{
			console.log('element not in database');
			if(catalogue[o.id] != undefined) {
				var p = catalogue[o.id];
				
				// update current product
				o.desc = p.desc;
				o.prod = p.prod;
				o.brand = p.brand;
				o.price = p.price;
				o.path = p.gridPathIndex;
			}
			
			//console.log(o);
			BasketDB.add(o);
		}
	},
	updateCurrentProductInfo: function(transaction, results) {
		myProduct = results.rows.item(0);
		console.log(myProduct);
		BasketDB.checkdo(myProduct, 'checkIfExist');
	},
	dataSelectHandler: function(transaction, results) {
		if(results.rows.length > 0) {
			$('#basket_items #scroller').text('');
			for (var i=0; i<results.rows.length; i++)
			{
				var o = results.rows.item(i);
				var output = itemoutput(o);

				$('#basket_items #scroller').append(output);
			}
		} 
		updateSum();
		updateNumberOfItems();
		
		$('.item', '#basket_items').trigger('webkitTransitionEnd');
		$('.item', '#basket_items').on('webkitTransitionEnd', function(e){
			var id = $(this).attr('id');
			BasketDB.remove(id.substr(1, id.length));
			$(this).remove();
			scroller.refresh();
		});
		
		if(scroller != null || scroller != undefined) scroller.refresh();
	},
	addToBasketHandler: function(transaction, results) {
		//console.log(results.rows.length)
		BasketDB.do('checkQtyHandler');
	},
	calcTotalHandler: function(transaction, results) {
		var total = new Number;
		for (var i=0; i<results.rows.length; i++)
		{
			var row = results.rows.item(i);

			var qty = row['qty'];
			var price = row['price'];
			
			total += Number(qty)*Number(price);
		}
		console.log(total);
	},
	removeHandler: function(transaction, results) {
		console.log('removed');
		updateNumberOfItems();
		BasketDB.do('checkQtyHandler');
	},
	checkQtyHandler: function(transaction, results) {
		var total = new Number();
		var sum = new Number();
		for(var i=0; i<results.rows.length; i++) {
			var o = results.rows.item(i); 
			total += o.qty;
			sum += (Number(o.qty) * Number(o.price));
		}
		$('#numBasketItems').text(total);
		$('#mybasket h2 .em').text('(' + total + ' item' + ( total < 2 ? ')' : 's)' ));
		$('#total .sum').text('$ ' + sum.toFixed(2)); 
	},
	nullDataHandler: function(transaction, result) {	
	},
	errorHandler: function(transaction, error) {
		console.log('SQL Error: ');
		console.log(error);
		return false;
	},
	check: function(id) {
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('SELECT id FROM basket WHERE id=?', [id], BasketDB.checkHandler, BasketDB.errorHandler);
			});
	},
	checkHandler: function(transaction, results) {
		console.log('number of element found: ' + results.rows.length);
	},
	addQty: function(id) {
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('SELECT qty, prod, price, id FROM basket WHERE id=?', [id], BasketDB.addQtyHandler, BasketDB.errorHandler);
			});
	},
	addQtyHandler: function(transaction, results) {
		var o = results.rows.item(0);
		var id = o['id'];
		var qty = o['qty'];
		var price = o['price'];
		BasketDB.update(id, {qty: (qty+1)});

		outputUpdate(id, (qty+1), price);
	},
	subQty: function(id) {
		this.BASKETDB.transaction(
			function(transaction) {
				transaction.executeSql('SELECT qty, prod, price, id FROM basket WHERE id=?', [id], BasketDB.subQtyHandler, BasketDB.errorHandler);
			});
	},
	subQtyHandler: function(transaction, results) {
		var o = results.rows.item(0);
		var id = o['id'];
		var qty = o['qty'];
		var price = o['price'];
		BasketDB.update(id, {qty: (qty-1 < 1 ? 1 : qty-1)});

		outputUpdate(id, (qty-1 < 1 ? 1 : qty-1), price);
	},
	tmp: undefined
};


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function itemoutput(o) {
	var output = '<div class="item" id="b' + o['id'] + '">';
		output += '<div class="td a"><img src="res/images/product/' + o.path + '/thumb/' + o.id + '.jpg" alt="product image"/></div>'
		output += '<div class="td b">'
		output += '<div class="ref">item: ' + o['id'] + '</div>';
		output += '<h4>' + o['prod'] + '</h4>';				
		output += '<em>' + o['brand'] + '</em>'
		output += '</div>';
		output += '<div class="td c"><em>16</em>/6/2012 to<br/><em>23</em>/6/2012</div>';
		output += '<div class="td d">$' + Number(o['price']).toFixed(2) + '</div>';
		output += '<div class="td e">';
		output += '<span class="ico sprite sub" onclick="subQty(this);"></span> <span class="myqty">' + o['qty'] + '</span> <span  onclick="addQty(this);" class="ico sprite add"></span>';
		output += '</div>';
		output += '<div class="td f">$' + Number(Number(o['qty']) * Number(o['price'])).toFixed(2) + '</div>'
		output += '<div class="td g"><a href="javascript:void(0);" title="remove" class="remove" onclick="removeItem(this);"><span class="sprite ico cross"></span></a></div>';
		output += '</div>';
		
	return output;
}
function outputUpdate(id, qty, price) {
	$('#b' + id + ' .myqty').html(qty);
	$('#b' + id + ' .f').html('$' + Number(qty*price).toFixed(2));
	//updateSum();
}
function addQty(elt) {
	var id = $(elt).parent().closest('.item').attr('id');
	var sku = id.substr(1, id.length);
	
	BasketDB.checkdo({id: sku}, 'addQtyHandler');
	/*var id = $($(elt).parents()[1]).attr('id');
	BasketDB.addQty(id);*/
}
function subQty(elt) {
	var id = $(elt).parent().closest('.item').attr('id');
	var sku = id.substr(1, id.length);
	
	BasketDB.checkdo({id: sku}, 'subQtyHandler');
	/*var id = $($(elt).parents()[1]).attr('id');
	BasketDB.subQty(id);*/
}
function updateSum() {
	BasketDB.do('checkQtyHandler');
}
function updateNumberOfItems() {
	//var o = $('#basket_items .item');
	//$('#mybasket h2 > .em').text('(' + o.length + ' item' + (o.length < 2 ? ')' : 's)'));
}
function removeItem(elt) {
	var me = $($(elt).parents()[1]);
	//var id = me.attr('id');
	$(me).css('opacity', 0);
	myProduct = {};
	//BasketDB.remove(id);
	//updateSum();
}
function addMeToBasket() {
	var o = {
		color: "0",
		id: "4038910",
		qty: 1,
		size: "M",
		prod: "Long Flare Jumpsuit",
		brand: "by Rare Fashion",
		price: "40.00",
		path: 4
	}
	
	BasketDB.checkdo(o, 'checkUpdateAdd');
	outputUpdate(o.id, Number($('#b' + o.id + ' .myqty').text())+1, o.price)

	if($('#b' + o.id).length == 0) {
		var output = itemoutput(o);

		$('#basket_items #scroller').append(output);

		updateSum();
		
		if(scroller != null || scroller != undefined) {
			scroller.refresh();
			scroller.scrollToElement('#basket_items .item:last-child', 100);		
		}
	}
}